import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CharacterEntity } from "../entities/character.entity";
import { CharacterEquipmentEntity } from "../entities/character-equipment.entity";
import { CharacterEquipmentInventoryEntity } from "../entities/character-equipment-inventory.entity";
import { EquipmentBaseEntity } from "../entities/equipment-base.entity";
import { CharacterAttributeService } from "./character-attribute.service";

@Injectable()
export class CharacterEquipmentService {
  constructor(
    @InjectRepository(CharacterEntity)
    private characterRepository: Repository<CharacterEntity>,
    @InjectRepository(CharacterEquipmentEntity)
    private equipmentRepository: Repository<CharacterEquipmentEntity>,
    @InjectRepository(CharacterEquipmentInventoryEntity)
    private inventoryRepository: Repository<CharacterEquipmentInventoryEntity>,
    @InjectRepository(EquipmentBaseEntity)
    private equipmentBaseRepository: Repository<EquipmentBaseEntity>,
    private characterAttributeService: CharacterAttributeService
  ) { }

  /**
   * 装备穿戴
   */
  async equipItem(characterId: number, equipmentId: number) {
    // 获取装备信息
    const equipment = await this.inventoryRepository.findOne({
      where: { id: equipmentId, characterId },
      relations: ["equipmentBase"],
    });

    if (!equipment) {
      throw new Error("装备不存在或不属于该角色");
    }

    if (equipment.status !== 1) {
      throw new Error("装备状态异常，无法穿戴");
    }

    // 获取装备基础数据
    const equipmentBase = equipment.equipmentBase;
    if (!equipmentBase) {
      throw new Error("装备基础数据不存在");
    }

    // 确定装备类型和对应的装备槽位
    const equipmentType = this.getEquipmentType(equipmentBase.type);
    if (!equipmentType) {
      throw new Error("未知的装备类型");
    }

    // 获取或创建角色装备记录
    let characterEquipment = await this.equipmentRepository.findOne({
      where: { characterId },
    });

    if (!characterEquipment) {
      characterEquipment = new CharacterEquipmentEntity();
      characterEquipment.characterId = characterId;
      characterEquipment.rightHand = null;
      characterEquipment.body = null;
      characterEquipment.head = null;
      characterEquipment.neck = null;
      characterEquipment.leftHand = null;
      characterEquipment.foot = null;
    }

    // 检查是否已有同类型装备，如果有则先卸下
    const currentEquippedId = characterEquipment[equipmentType];
    if (currentEquippedId) {
      await this.unequipItem(characterId, equipmentType);
    }

    // 穿戴新装备
    characterEquipment[equipmentType] = equipmentId;
    await this.equipmentRepository.save(characterEquipment);

    // 更新装备状态为已装备
    equipment.status = 0; // 0表示已使用/已装备
    await this.inventoryRepository.save(equipment);

    return {
      success: true,
      message: "装备穿戴成功",
      equipmentType,
      equipmentId,
    };
  }

  /**
   * 卸下装备
   */
  async unequipItem(characterId: number, equipmentType: string) {
    const characterEquipment = await this.equipmentRepository.findOne({
      where: { characterId },
    });

    if (!characterEquipment) {
      return { success: true, message: "没有装备可卸下" };
    }

    const equipmentId = characterEquipment[equipmentType];
    if (!equipmentId) {
      return { success: true, message: "该位置没有装备" };
    }

    // 更新装备状态为正常
    await this.inventoryRepository.update(
      { id: equipmentId },
      { status: 1 } // 1表示正常状态
    );

    // 清空装备槽位
    characterEquipment[equipmentType] = null;
    await this.equipmentRepository.save(characterEquipment);

    return {
      success: true,
      message: "装备卸下成功",
      equipmentType,
      equipmentId,
    };
  }

  /**
   * 根据装备类型ID确定装备槽位
   */
  private getEquipmentType(typeId: number): string | null {
    const typeMapping: Record<number, string> = {
      1: "head", // 头盔
      2: "rightHand", // 武器
      3: "body", // 铠甲
      4: "neck", // 项链
      5: "leftHand", // 护腕
      6: "foot", // 战靴
    };

    return typeMapping[typeId] || null;
  }

  /**
   * 获取角色当前装备信息
   */
  async getCharacterEquipment(characterId: number) {
    const characterEquipment = await this.equipmentRepository.findOne({
      where: { characterId },
      relations: [
        "rightHandEquipment",
        "bodyEquipment",
        "headEquipment",
        "neckEquipment",
        "leftHandEquipment",
        "footEquipment",
      ],
    });

    if (!characterEquipment) {
      return {
        right_hand: null,
        body: null,
        head: null,
        neck: null,
        left_hand: null,
        foot: null,
        fight: false,
      };
    }

    const formatEquipment = (equipment: any) => {
      if (!equipment) return null;
      return {
        id: equipment.id,
        lvl: equipment.level,
        name: equipment.name,
        p: equipment.pic,
      };
    };

    return {
      right_hand: formatEquipment(characterEquipment.rightHandEquipment),
      body: formatEquipment(characterEquipment.bodyEquipment),
      head: formatEquipment(characterEquipment.headEquipment),
      neck: formatEquipment(characterEquipment.neckEquipment),
      left_hand: formatEquipment(characterEquipment.leftHandEquipment),
      foot: formatEquipment(characterEquipment.footEquipment),
      fight: false,
    };
  }

  /**
   * 检查装备需求
   */
  async checkEquipmentRequirements(characterId: number, equipmentId: number) {
    const character = await this.characterRepository.findOne({
      where: { id: characterId },
      relations: ["attributes", "attributePoints"],
    });

    if (!character) {
      throw new Error("角色不存在");
    }

    const equipment = await this.inventoryRepository.findOne({
      where: { id: equipmentId, characterId },
      relations: ["equipmentBase"],
    });

    if (!equipment || !equipment.equipmentBase) {
      throw new Error("装备不存在");
    }

    const base = equipment.equipmentBase;

    // 使用 calculateCharacterAttributes 方法获取计算后的属性
    const calculatedAttributes = await this.characterAttributeService.calculateCharacterAttributes(characterId);
    const attributePoints = character.attributePoints || {
      strength: 0,
      constitution: 0,
      intelligence: 0,
      agility: 0,
    };

    const requirements = {
      level: base.req_level || 0,
      strength: base.req_strength || 0,
      constitution: base.req_constitution || 0,
      intelligence: base.req_intelligence || 0,
      agility: base.req_agility || 0,
    };

    // 使用计算后的属性点（等级 + 已分配属性点）
    const current = {
      level: character.lvl,
      strength: character.lvl + attributePoints.strength,
      constitution: character.lvl + attributePoints.constitution,
      intelligence: character.lvl + attributePoints.intelligence,
      agility: character.lvl + attributePoints.agility,
    };

    const canEquip =
      current.level >= requirements.level &&
      current.strength >= requirements.strength &&
      current.constitution >= requirements.constitution &&
      current.intelligence >= requirements.intelligence &&
      current.agility >= requirements.agility;

    return {
      canEquip,
      requirements,
      current,
      equipment: {
        id: equipment.id,
        name: equipment.name,
        level: equipment.level,
        type: base.type,
      },
    };
  }
}
